package com.xysq.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.rockcent.action.CallbackListener;
import com.rockcent.model.CouponBO;
import com.rockcent.model.SearchBO;
import com.umeng.analytics.MobclickAgent;
import com.xysq.adapter.SearchAdapter;
import com.xysq.adapter.SearchListAdapter;
import com.xysq.lemon.R;
import com.xysq.util.DBHelper;
import com.xysq.util.ToastUtil;
import com.xysq.util.UserInfoKeeper;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.InjectView;

/**
 * Created by huangdongkai on 2015/8/7.
 */
public class SearchActivity extends BaseActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener, AbsListView.OnScrollListener {
    @InjectView(R.id.edt_search)
    EditText searchEdt;
    @InjectView(R.id.iv_search)
    ImageView searchIv;
    @InjectView(R.id.list_data_history)
    ListView dataHistoryList;
    @InjectView(R.id.list_data_search)
    ListView dataSearchList;
    @InjectView(R.id.ibtn_back)
    ImageButton backIbtn;
    @InjectView(R.id.layout_search_history)
    LinearLayout searchHistoryLayout;
    @InjectView(R.id.layout_search)
    LinearLayout searchLayout;
    @InjectView(R.id.btn_first_search)
    Button firstSearchBtn;
    @InjectView(R.id.btn_second_search)
    Button secondSearchBtn;
    @InjectView(R.id.btn_third_search)
    Button thirdSearchBtn;
    @InjectView(R.id.swp_fresh)
    SwipeRefreshLayout freshSwp;
    @InjectView(R.id.layout_reloading)
    LinearLayout reloadingLayout;
    @InjectView(R.id.layout_loading)
    LinearLayout loadingLayout;
    @InjectView(R.id.layout_empty_quan)
    LinearLayout emptyQuanLayout;
    @InjectView(R.id.layout_category)
    LinearLayout categoryLayout;
    @InjectView(R.id.txt_category)
    TextView categoryTxt;

    private SearchAdapter searchAdapter;
    private SearchListAdapter searchListAdapter;
    private Set<String> set;
    private String xyCustomerId;
    private String category = "";//B_B端的券；C_C端的券（空或不传为所有类型）
    private View footerView;
    private boolean isProgressing = true;
    private boolean hasMoreData = false;
    private PopupWindow popupWindow;
    private LinearLayout versatileLayout;
    private LinearLayout availableLayout;
    private ImageView youcaiIv;
    private ImageView youhuoIv;
    private TextView youcaiTxt;
    private TextView youhuoTxt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        initView();
        getData();
    }

    public void initFooterView() {
        footerView = getLayoutInflater().inflate(R.layout.load_more_footer, dataSearchList, false);
        //此处添加footerview是为了防止类型转换错误
        dataSearchList.addFooterView(footerView);
    }


    private void initView() {
        reloadingLayout.setOnClickListener(this);
        searchIv.setOnClickListener(this);
        backIbtn.setOnClickListener(this);
        searchAdapter = new SearchAdapter(this);
        dataHistoryList.setAdapter(searchAdapter);
        initFooterView();//加载底部
        freshSwp.setOnRefreshListener(this);
        freshSwp.setColorSchemeResources(
                android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        searchListAdapter = new SearchListAdapter(this);
        dataSearchList.setAdapter(searchListAdapter);
        dataSearchList.removeFooterView(footerView);
        freshSwp.setRefreshing(false);
        firstSearchBtn.setOnClickListener(this);
        secondSearchBtn.setOnClickListener(this);
        thirdSearchBtn.setOnClickListener(this);
        dataSearchList.setOnScrollListener(this);
        categoryLayout.setOnClickListener(this);
        dataSearchList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                MobclickAgent.onEvent(SearchActivity.this, "1032");
                CouponBO couponBO = (CouponBO) searchListAdapter.getItem(i);
                if (couponBO.getCategory() != null) {
                    if (couponBO.getCategory().equals("B")) {
                        Intent intent = new Intent(SearchActivity.this, CommodityDetailsActivity.class);
                        intent.putExtra(CommodityDetailsActivity.COUPONMODEL_ID, couponBO.getId());
                        startActivity(intent);
                    } else if (couponBO.getCategory().equals("C")) {
//                        Intent intent = new Intent(SearchActivity.this, TipsActivity.class);
//                        intent.putExtra(TipsActivity.COUPONMODEL_ID, couponBO.getId());
//                        intent.putExtra(TipsActivity.CUSTOMER_ID, couponBO.getCustomerId());
//                        startActivity(intent);
                        if(couponBO.getIssueCount().equals("0")) {//判断技能和贴士进入不同的界面
                            Intent intent = new Intent(SearchActivity.this, TipsActivity.class);
                            intent.putExtra(TipsActivity.COUPONMODEL_ID, couponBO.getId());
                            intent.putExtra(TipsActivity.CUSTOMER_ID, couponBO.getCustomerId());
                            startActivity(intent);
                        }else {
                            Intent intent = new Intent(SearchActivity.this, TipsActivity.class);
//                            Intent intent = new Intent(SearchActivity.this, CustomerCouponDetailActivity.class);
                            intent.putExtra(CustomerCouponDetailActivity.COUPONMODEL_ID, couponBO.getId());
                            intent.putExtra(CustomerCouponDetailActivity.CUSTOMER_ID, couponBO.getCustomerId());
                            startActivity(intent);
                        }
                    }
                } else {
                    ToastUtil.showShort(SearchActivity.this, "查询出错");
                }
            }
        });
        dataHistoryList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                loadingLayout.setVisibility(View.VISIBLE);
                SearchBO searchBO = (SearchBO) searchAdapter.getItem(i);
                searchEdt.setText(searchBO.getName());
                getSearchResult();
            }
        });
    }

    private void getData() {
        xyCustomerId = UserInfoKeeper.readCustomerId(this);
        getSearchHot();
        getSearchHistory();
    }

    //热搜条件
    private void getSearchHot() {

    }

    //获取本地搜索历史
    private void getSearchHistory() {
        List<SearchBO> searchBOList = dbHelper.getSearchHistory(dbHelper.SEARCH_HISTORY);
        if (searchBOList.size() > 0) {
            searchHistoryLayout.setVisibility(View.VISIBLE);
        } else {
            searchHistoryLayout.setVisibility(View.GONE);
        }
        searchAdapter.setItems(searchBOList);
    }

    //加入本地搜索历史
    private void putSearchHistroy(String searchHistory) {
        if (!TextUtils.isEmpty(searchHistory)) {
            List<SearchBO> searchBOList = dbHelper.getSearchHistory(dbHelper.SEARCH_HISTORY);
            if (searchBOList.size() > 0) {
                for (int i = 0; i < searchBOList.size(); i++) {
                    SearchBO searchBO = searchBOList.get(i);
                    if (searchHistory.trim().equals(searchBO.getName().trim())) {//已存在记录，删除以前的，添加现在的。
                        dbHelper.deleteDatas(dbHelper.SEARCH_HISTORY, "name", searchHistory);
                    }
                }
            }
            Map<String, Map<String, Object>> parentMap = new LinkedHashMap<String, Map<String, Object>>();
            Map<String, Object> childMap = new LinkedHashMap<String, Object>();
            childMap.put("name", searchHistory);
            childMap.put("createTime", System.currentTimeMillis());
            parentMap.put(DBHelper.PARENT + 0, childMap);
            dbHelper.insertData(dbHelper.SEARCH_HISTORY, parentMap);
        }
    }

    //搜素
    private void getSearchResult() {
        searchLayout.setVisibility(View.GONE);
        putSearchHistroy(searchEdt.getText().toString());
        String searchCategory = categoryTxt.getText().toString();
       if(searchCategory.equals(getResources().getString(R.string.txt_category_youcai))) {
           category = "C";
        } else if(searchCategory.equals(getResources().getString(R.string.txt_category_youhuo))) {
            category = "B";
        }
        appAction.searchCoupon4Page(xyCustomerId, category, searchEdt.getText().toString(), currentPage, PAGE_SIZE, new CallbackListener<List<CouponBO>>() {
            @Override
            public void onSuccess(List<CouponBO> data) {
                if (data.size() > 0) {
                    if (currentPage > 1) {
                        searchListAdapter.addItems(data);
                    } else {
                        searchListAdapter.setItems(data);
                    }
                    dataSearchList.setVisibility(View.VISIBLE);
                    searchLayout.setVisibility(View.GONE);
                    if (data.size() == PAGE_SIZE) {
                        dataSearchList.addFooterView(footerView);
                        hasMoreData = true;
                    } else {
                        dataSearchList.removeFooterView(footerView);
                        hasMoreData = false;
                    }
                    freshSwp.setRefreshing(false);
                    emptyQuanLayout.setVisibility(View.GONE);
                } else if (searchListAdapter.getCount() == 0) {
                    emptyQuanLayout.setVisibility(View.VISIBLE);
                }
                loadingLayout.setVisibility(View.GONE);
            }

            @Override
            public void onFailure(String errorCode, String message) {
                ToastUtil.showShort(SearchActivity.this, message);
                freshSwp.setRefreshing(false);
                loadingLayout.setVisibility(View.GONE);
                reloadingLayout.setVisibility(View.VISIBLE);
                emptyQuanLayout.setVisibility(View.GONE);
            }
        });
       /* appAction.listCouponModel(searchEdt.getText().toString(), modelType, listType, industryId, currentPage, PAGE_SIZE, locationId, new CallbackListener<List<CouponBO>>() {
            @Override
            public void onSuccess(List<CouponBO> data) {
                Log.d("test", data.size() + "size");
                if (data.size() > 0) {
                    searchListAdapter.setItems(data);
                    dataSearchList.setVisibility(View.VISIBLE);
                    searchLayout.setVisibility(View.GONE);
                } else {
                    ToastUtil.showShort(SearchActivity.this, "无搜索结果");
                }
            }

            @Override
            public void onFailure(String errorCode, String message) {
                ToastUtil.showShort(SearchActivity.this, message);
            }
        });*/
    }

    @Override
    public void onClick(View view) {
        if (view == searchIv) {
            if (TextUtils.isEmpty(searchEdt.getText().toString())) {
                ToastUtil.showShort(this, getResources().getString(R.string.toast_empty_search));
                return;
            }
            MobclickAgent.onEvent(this, "1032");
            emptyQuanLayout.setVisibility(View.GONE);
            loadingLayout.setVisibility(View.VISIBLE);
            currentPage = 1;
            searchListAdapter.clearItems();
            getSearchResult();
        }
        if (view == backIbtn) {
            finish();
        }
        if (view == firstSearchBtn) {
            MobclickAgent.onEvent(this, "1032");
            loadingLayout.setVisibility(View.VISIBLE);
            searchEdt.setText(firstSearchBtn.getText().toString());
            getSearchResult();
        }
        if (view == secondSearchBtn) {
            MobclickAgent.onEvent(this, "1032");
            loadingLayout.setVisibility(View.VISIBLE);
            searchEdt.setText(secondSearchBtn.getText().toString());
            getSearchResult();
        }
        if (view == thirdSearchBtn) {
            MobclickAgent.onEvent(this, "1032");
            loadingLayout.setVisibility(View.VISIBLE);
            searchEdt.setText(thirdSearchBtn.getText().toString());
            getSearchResult();
        }
        if (view == reloadingLayout) {
            loadingLayout.setVisibility(View.VISIBLE);
            reloadingLayout.setVisibility(View.GONE);
            getSearchResult();
        }
        if (view == categoryLayout) {
            showPopupWindow();
        }
        if (view == versatileLayout) {
            categoryTxt.setText(getResources().getString(R.string.txt_category_youcai));
//            changeStyle(0);
            popupWindow.dismiss();
        }
        if (view == availableLayout) {
            categoryTxt.setText(getResources().getString(R.string.txt_category_youhuo));
//            changeStyle(1);
            popupWindow.dismiss();
        }
    }

    //改变有货有才点击事件
    private void changeStyle(int type) {
        switch (type) {
            case 0:
                youcaiIv.setImageResource(R.drawable.ic_search_youcai_blue);
                youcaiTxt.setTextColor(getResources().getColor(R.color.bg_btn_blue));
                youhuoIv.setImageResource(R.drawable.ic_search_youhuo_white);
                youhuoTxt.setTextColor(getResources().getColor(R.color.txt_white));
                break;
            case 1:
                youhuoIv.setImageResource(R.drawable.ic_search_youhuo_blue);
                youhuoTxt.setTextColor(getResources().getColor(R.color.bg_btn_blue));
                youcaiIv.setImageResource(R.drawable.ic_search_youcai_white);
                youcaiTxt.setTextColor(getResources().getColor(R.color.txt_white));
                break;
        }
    }

    //弹出下拉列表
    private void showPopupWindow() {
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.pop_search, null);
        WindowManager wm = this.getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        popupWindow = new PopupWindow(contentView,
                width - 500, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setTouchable(true);
/*        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);*/
        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.black));
/*        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });*/
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(new View(this), Gravity.NO_GRAVITY, 100, 140);
        versatileLayout = (LinearLayout) contentView.findViewById(R.id.layout_versatile);
        availableLayout = (LinearLayout) contentView.findViewById(R.id.layout_available);
        youcaiIv = (ImageView) contentView.findViewById(R.id.iv_youcai);
        youhuoIv = (ImageView) contentView.findViewById(R.id.iv_youhuo);
        youcaiTxt = (TextView) contentView.findViewById(R.id.txt_youcai);
        youhuoTxt = (TextView) contentView.findViewById(R.id.txt_youhuo);
        versatileLayout.setOnClickListener(this);
        availableLayout.setOnClickListener(this);
    }

    @Override
    public void onRefresh() {
        currentPage = 1;
        searchListAdapter.clearItems();
        loadingLayout.setVisibility(View.VISIBLE);
        getSearchResult();
    }

    @Override
    public void onScrollStateChanged(AbsListView absListView, int scrollState) {
//        if (!isProgressing && hasMoreData && scrollState == SCROLL_STATE_IDLE
        if (hasMoreData && scrollState == SCROLL_STATE_IDLE
                && (absListView.getLastVisiblePosition() >= absListView.getCount() - 1)) {
            currentPage++;
            getSearchResult();
        }
    }

    @Override
    public void onScroll(AbsListView absListView, int i, int i1, int i2) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("搜索页");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("搜索页");
        MobclickAgent.onPause(this);
    }

    @Override
    public void finish() {
        Intent intent = new Intent(this,MainTabActivity.class);
        intent.putExtra(MainTabActivity.INDEX,MainTabActivity.TAG_INDEX);
        startActivity(intent);
    }
}
